import java.nio.charset.StandardCharsets;

import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

public class shiyan3_2 {

    public static final String key = "jkl;POIU1234++==";
    public static final byte[] rand = {1,2,3,4,5,6,7,8};
    /*
     * main函数
     * */
    public static void main(String[] args) throws Exception {
        if(args.length!=3){
            System.out.println("请输入三个参数");
            return;
        }
        if(args[0].equals("ENC")){encryptFile(args[1],args[2],key);
        }
        else if(args[0].equals("DEC")){
            decryptFile(args[1],args[2],key);
        }
    }

    /*
     * infile 输入文件名称
     * outfile 输出文件名称
     * key 密钥
     * 这个函数里面没有任何逻辑可言,整个就是调用外部的库
     * */

    public static void encryptFile(String infile,String outfile,String key) throws Exception {

        FileInputStream finput = new FileInputStream(infile);
        int num = finput.available();
        byte[] indata = new byte[num];
        finput.read(indata);

	String data = new String(indata);
	char[] password = key.toCharArray();
	PBEKeySpec pbks = new PBEKeySpec(password);
	SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
	SecretKey k = kf.generateSecret(pbks);
	Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");
	PBEParameterSpec ps = new PBEParameterSpec(rand,1000);
	cp.init(Cipher.ENCRYPT_MODE,k,ps);
	byte[] inda = data.getBytes("UTF8");
	byte[] outda = cp.doFinal(inda);
	FileOutputStream foutput = new FileOutputStream(outfile);
	foutput.write(outda);
	finput.close();
	foutput.close();
    }

    /*
     * infile 要解密的文件
     * outfile 解密后的文件
     * key 密钥
     * */
    public static void decryptFile(String infile,String outfile,String key) throws Exception {

	//获取密钥
	char[] password = key.toCharArray();
	PBEKeySpec pbks = new PBEKeySpec(password);

	//获取需要解密的文件
        FileInputStream finput = new FileInputStream(infile);
        int num = finput.available();
        byte[] indata = new byte[num];
        finput.read(indata);

	SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
	SecretKey k = kf.generateSecret(pbks);
	Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");
	PBEParameterSpec ps = new PBEParameterSpec(rand,1000);
	cp.init(Cipher.DECRYPT_MODE,k,ps);
	byte[] outda = cp.doFinal(indata);
	FileOutputStream foutput = new FileOutputStream(outfile);
	foutput.write(rand);
	foutput.write(outda);
	finput.close();
	foutput.close();
    }
}
